<template>
  <!-- 科技推广及技术研发策划表 -->
  <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel == 0 ? {} : rules">
    <a-spin :spinning="loading">
      <!-- 表单 -->
      <a-card>
        <title-name title="科技推广及技术研发策划表"></title-name>
        <a-button :disabled="editModel == 0" type="primary" class="mb12" icon="plus" @click="addTabel"> 新增 </a-button>
        <s-table bordered ref="table" size="default" rowKey="key" :columns="columns" :data="loadData" :alert="true" show-size-changer show-quick-jumper :showPagination="false">
          <template slot="action" slot-scope="text, record, index">
            <a-popconfirm title="确定要删除?" @confirm="() => delItem(index)">
              <a :disabled="editModel == 0 || record.isDeleted == 1">删除</a>
            </a-popconfirm>
          </template>
          <template v-for="col in ['name', 'planName', 'completeTime', 'principal', 'remark']" :slot="col" slot-scope="text, record">
            <div :key="col" class="form-item">
              <a-month-picker v-if="col === 'completeTime'" v-model="record[col]" :disabled="editModel == 0" placeholder="请选择" value-format="YYYY-MM" />

              <ASelectOrgPeople v-else-if="col === 'principal'" :disabled="editModel == 0" :init="false" :form="baseFormInfo" key-value="projectOrgId" option-key="id" v-model="record[col]"></ASelectOrgPeople>
              <BaseInput v-else :class="col === 'remark' ? 'remark' : ''" v-model="record[col]" :disabled="editModel == 0" />
            </div>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <DialogForm
      ref="dialogForm"
      :visible.sync="visible"
      :edit-model="'2'"
      :form="initData"
      header-title="增加科技推广及技术研发类型"
      :width="800"
      :height="1100"
      :isEmit="false"
      :rules="rulesDialog"
      :form-list="formListDialog"
      @confirm="submitForm"
      :clearForm="false"
      :styles="{ width: '550px' }"
    />
  </a-form-model>
   
</template>

<script>
import { api } from '@/api/projectManagementPlanning/sciencePromoteTable'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
import DialogForm from '@/components/DialogForm' // 弹窗

export default {
  name: 'projectAuthorizationLetter',
  extends: new BaseEditPage(),
  components: {
    SelectProject,
    BSelect,
    SelectSubCompany,
    ASelectOrgPeople,
    DialogForm
  },
  props: {
    baseFormInfo: {
      // 是否作为审批详情
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 1, // 操作状态:0 查看;1 编辑
      form: { data: [] }, // 表单
      id: '',
      initData: { type: undefined, typeTwo: undefined, num: 1 },
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.data || []
          })
        })
      },
      update: api.updateList,
      rules: {}, // 校验规则
      rulesDialog: {
        typeTwo: [{ required: true, message: '请选择' }],
        num: [{ required: true, message: '请输入' }]
      },
      init: false // 初始化控件
    }
  },
  watch: {},
  computed: {
    formListDialog() {
      return [
        // 手写普通选择框
        {
          type: 'a-select',
          keyName: 'typeTwo',
          label: '类型',
          span: 24,
          data: [
            {
              value: '研发类',
              label: '研发类'
            },
            {
              value: '新技术',
              label: '新技术'
            },
            {
              value: '新工艺',
              label: '新工艺'
            },
            {
              value: '新材料',
              label: '新材料'
            },
            {
              value: '新设备',
              label: '新设备'
            }
          ]
        },
        {
          keyName: 'num',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          span: 24,
          label: '行数',
          attrs: {
            min: 0,
            isInt: true
          }
        }
      ]
    },
    columns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          customRender(text, record, index) {
            return index + 1
          }
        },
        {
          title: '类型',
          dataIndex: 'type',
          colSpan: 2,
          width: '10%',
          customRender: (text, row, index) => {
            let obj = {
              children: text,
              attrs: {}
            }
            let lastIndex = -1
            let firstIndex = this.form.data.findIndex((v) => v.type === text)
            this.form.data.map((m, i) => {
              if (m.type == text) {
                lastIndex = i
              }
            })
            if (index === 0) {
              obj.attrs.colSpan = 2
              obj.attrs.rowSpan = lastIndex === firstIndex ? 1 : lastIndex + 1 - firstIndex
            } else {
              // 若该行考核内容和上一行一致，则使其隐藏
              if (this.form.data[index - 1].type === text) {
                obj.attrs.rowSpan = 0
                // 若不是，则往下合并与改行内容一致行的总行数
              } else {
                obj.attrs.rowSpan = lastIndex === firstIndex ? 1 : lastIndex + 1 - firstIndex
              }
            }

            return obj
          }
        },
        {
          title: '类型子',
          colSpan: 0,
          dataIndex: 'typeTwo',
          customRender: (text, row, index) => {
            let obj = {
              children: text,
              attrs: {}
            }

            if (this.form.data[index].type == '研发类') {
              obj.attrs.colSpan = 0
            }
            let lastIndex = -1
            let firstIndex = this.form.data.findIndex((v) => v.typeTwo === text)
            this.form.data.map((m, i) => {
              if (m.typeTwo == text) {
                lastIndex = i
              }
            })

            // 若该行考核内容和上一行一致，则使其隐藏
            if (index > 0 && this.form.data[index - 1].typeTwo == text) {
              obj.attrs.rowSpan = 0
              // 若不是，则往下合并与改行内容一致行的总行数
            } else {
              obj.attrs.rowSpan = lastIndex === firstIndex ? 1 : lastIndex + 1 - firstIndex
            }

            return obj
          }
        },
        {
          title: '计划研发或应用的四新技术',
          dataIndex: 'planName',
          width: '25%',
          scopedSlots: { customRender: 'planName' }
        },
        {
          title: '责任人',
          dataIndex: 'principal',
          width: '15%',
          scopedSlots: { customRender: 'principal' }
        },
        {
          title: '完成时间',
          width: '13%',
          dataIndex: 'completeTime',
          scopedSlots: { customRender: 'completeTime' }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          scopedSlots: { customRender: 'remark' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '8%',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  created() {},
  mounted() {
    // 不为添加时请求详情
    this.getDetailData()
  },

  methods: {
    addTabel() {
       this.initData.typeTwo = undefined
      this.visible = true
      this.$nextTick(() => {
        const requireDom = document.querySelectorAll('.ant-form-item-required')
        const requireDomArray = Array.from(requireDom)
        requireDomArray.forEach((item) => {
          item.parentNode.nextSibling.children[0].children[0].classList.add('requiredFormItem') // 找到'.ant-form-item-children'元素添加样式
        })
      })
    },
    submitForm(data) {
      let index = 0

      if (data.typeTwo != '研发类') {
        data.type = '四新技术'
      } else {
        data.type = '研发类'
        data.typeTwo = ''
      }
      console.log(data)
      this.form.data.forEach((e, i) => {
        // 研发类没有typeTwo, 无法用type作比较
        if (data.type == '研发类') {
          if (data.type == e.type) {
            index = i
          }
        } else {
          if (data.typeTwo == e.typeTwo) {
            index = i
          }
        }
      })
      for (let i = 1; i < data.num; i++) {
        this.form.data.splice(index + i, 0, {
          type: data.type,
          typeTwo: data.typeTwo,
          mainId: this.id,
          completeTime: '',
          planName: '',
          principal: '',
          remark: ''
        })
      }
      this.form.data.splice(index + 1, 0, {
        type: data.type,
        typeTwo: data.typeTwo,
        mainId: this.id,
        completeTime: '',
        planName: '',
        principal: '',
        remark: ''
      })
      this.visible = false
      this.$refs.table.refresh()
    },

    getDetailData() {
      this.loading = true
      api
        .getDetails({ id: this.id, version: this.$route.query.version || void 0 })
        .then((res) => {
          this.loading = false
          this.form = res
          console.log(this.form)
          this.$refs.table.refresh()
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    },

    validateForm() {
      let flag = true
      if (this.form.data.length > 0) {
        this.form.data.forEach((i) => {
          if (!i.planName || !i.completeTime || !i.principal) {
            flag = false
          }
        })
        if (!flag) {
          this.$warning({
            title: '提示',
            content: '请将数据填写完整!',
            okText: '确定'
          })
        }
      } else {
        this.$warning({
          title: '提示',
          content: '请至少填写一行数据!',
          okText: '确定'
        })
        flag = false
      }

      return flag
    },
    delItem(index) {
      this.form.data.splice(index, 1)
      this.$refs.table.refresh()
    },
    sciencePromoteTableSaveDrafts() {
      this.handleSubmit(0)
    },
    sciencePromoteTableSubmit() {
      if (this.validateForm()) {
        this.handleSubmit(1)
      }
    },

    /**
     * 提交表单
     */
    handleSubmit(status) {
      let form = this.$clone(this.form)
      console.log(form)
      if (form.data.length == 0) {
        form.data.push({ mainId: this.id })
      }
      form.data[0].status = status
      if (status == 1) {
        this.handleSecondSub(form.data)
        return
      }
      this.loading = true
      api
        .updateList(form.data)
        .then(() => {
          this.loading = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          this.$multiTab.close()
        })
        .catch(() => {
          this.loading = false
          this.$message.warning(err.data.message)
        })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
</style>